package com.ruoyi.jiuyezu.service.impl;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.jiuyezu.domain.*;
import com.ruoyi.jiuyezu.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.jiuyezu.service.IRegistersService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 就业组抽背登记记录Service业务层处理
 *
 * @author wyj
 * @date 2024-07-23
 */
@Service
public class RegistersServiceImpl implements IRegistersService {
    @Autowired
    private RegistersMapper registersMapper;
    @Resource
    private QuizResultsMapper quizResultsMapper;
    @Resource
    private StudentsMapper studentsMapper;
    @Resource
    private ClassesMapper classesMapper;
    @Resource
    private QuestionsMapper questionsMapper;


    /**
     * 查询就业组抽背登记记录
     *
     * @param registerId 就业组抽背登记记录主键
     * @return 就业组抽背登记记录
     */
    @Override
    public Registers selectRegistersByRegisterId(Long registerId) {
        return registersMapper.selectRegistersByRegisterId(registerId);
    }

    /**
     * 查询就业组抽背登记记录列表
     *
     * @param registers 就业组抽背登记记录
     * @return 就业组抽背登记记录
     */
    @Override
    public List<Registers> selectRegistersList(Registers registers) {
        return registersMapper.selectRegistersList(registers);
    }

    /**
     * 新增就业组抽背登记记录
     *
     * @param registers 就业组抽背登记记录
     * @return 结果
     */
    @Override
    public int insertRegisters(Registers registers) {
        return registersMapper.insertRegisters(registers);
    }

    /**
     * 修改就业组抽背登记记录
     *
     * @param registers 就业组抽背登记记录
     * @return 结果
     */
    @Override
    public int updateRegisters(Registers registers) {
        return registersMapper.updateRegisters(registers);
    }

    /**
     * 批量删除就业组抽背登记记录
     *
     * @param registerIds 需要删除的就业组抽背登记记录主键
     * @return 结果
     */
    @Override
    public int deleteRegistersByRegisterIds(Long[] registerIds) {
        return registersMapper.deleteRegistersByRegisterIds(registerIds);
    }

    /**
     * 删除就业组抽背登记记录信息
     *
     * @param registerId 就业组抽背登记记录主键
     * @return 结果
     */
    @Override
    public int deleteRegistersByRegisterId(Long registerId) {
        return registersMapper.deleteRegistersByRegisterId(registerId);
    }

    @Override
    @Transactional
    public void insertRegistersList(List<Registers> registersList) {
        //把学生、题目、班级都插入到不同的表中


        //把数据插入到jiuyezu_registers表中
        for (Registers registers : registersList) {
            Classes classByName = classesMapper.selectClassByName(registers.getClasses());
            if (classByName == null) {
                Classes classes = new Classes();
                classes.setClassName(registers.getClasses());
                classes.setTerm("S3");
                classesMapper.insertJiuyezuClasses(classes);
                //通过Mybatis自动生成的id为classByName.setId()

            }

            Long classId = classesMapper.selectClassByName(registers.getClasses()).getId();

            //把数据插入到jiuyezu_students表中
            if (studentsMapper.selectStudentsByName(registers.getName()) == null) {
                Students students = new Students();
                students.setStudentName(registers.getName());
                students.setClassId(classId);

                studentsMapper.insertStudents(students);
            }

            //把数据插入到jiuyezu_questions表中

            //错误题目的数量（一个人错误题目的数量）
            long errorCount = 0;
            //错题抄写次数（班上三个人错误题目的数量）,数据库的记录是按照一个人来记录的，不能记录班级的数量
//            long copyCount = 0;
            //需要抄写的错误题目数量（错误数*5）（一个人需要抄写的次数）
            long errorCopyCount = 0;
            String[] split = registers.getWrongQuestions().split(";");
            errorCount = split.length;
            errorCopyCount = errorCount * 5;

//            Map<String, Map<String, Long>> classErrorCounts = new HashMap<>();
//            Map<String, Long> studentErrors = classErrorCounts.computeIfAbsent(registers.getClasses(), k -> new HashMap<>());
//            // 统计个人错误题目数量
//            studentErrors.put(registers.getName(), errorCount);
//            // 统计班级错误题目总数
//            long totalClassErrors = classErrorCounts.values().stream()
//                    .flatMap(map -> map.values().stream()) // 将Map的值转换为Stream
//                    .mapToLong(Long::longValue) // 将Stream中的对象转换为LongStream
//                    .sum();
//            copyCount = totalClassErrors;

            for (String s : split) {
                Questions questions = new Questions();
                questions.setQuestionName(s);
                if (!s.equals("") && !s.equals("全对"))  questionsMapper.insertJiuyezuQuestions(questions);
            }

            //把数据在插一遍到jiuyezu_check_results中，同时计算错误次数和抄写的次数
            //jiuyezu_check_results用于导出Excel，jiuyezu_registers有些字段没有
            QuizResults quizResults = new QuizResults();
            quizResults.setQuizDate(registers.getDate());
            quizResults.setIsCopied(registers.getIsCompleted());
            quizResults.setStudentName(registers.getName());
            quizResults.setClassId(classId);
            quizResults.setRemark(registers.getWrongQuestions());
            quizResults.setErrorCount(errorCount);
            quizResults.setErrorCopyCount(errorCopyCount);
//            quizResults.setCopyCount(copyCount);

            quizResultsMapper.insertQuizResults(quizResults);
            registersMapper.insertRegisters(registers);
        }
    }
}
